package com.zige.zige.view;

import java.lang.ref.WeakReference;
import java.util.Formatter;
import java.util.HashMap;
import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;

import com.zige.zige.R;
import com.zige.zige.activity.BaseActivity;
import com.zige.zige.constants.Constants;
import com.zige.zige.constants.UrlConsts;
import com.zige.zige.pojo.UserInfo;
import com.zige.zige.task.MyPostRequestTask;
import com.zige.zige.task.PostRequestTask;
import com.zige.zige.task.TaskExecutor;
import com.zige.zige.utils.SharedPreferencesUtils;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.media.AudioManager;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.MotionEventCompat;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityNodeInfo;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;

public class Controller extends FrameLayout {

    private static final String LOG_TAG = Controller.class.getName();

    private static final int FADE_OUT = 1;
    private static final int DEFTIMEOUT = 5000;
    private static final int SHOW_PROGRESS = 2;

    private ImageButton mBtnPause;

    private ImageButton mBtnNext;
    private ImageButton mBtnPrev;
    public ImageView mBtnFullscreen;
    private Handler mHandler = new MsgHandler(this);

    private ControlOper mPlayerCtrl;
    private Context mContext;
    private ViewGroup mAnchorVGroup;
    private View mRootView;
    private SeekBar mProgress;
    private TextView mEndTime, mCurTime;
    private boolean mIsShowing;
    private boolean mIsDragging;
    private boolean mUseFastForward;
    private boolean mFromXml;
    private boolean mIsListenersSet;
    private View.OnClickListener mNextListener, mPrevListener, mFullScreenListener;
    StringBuilder mStrBuilder;
    Formatter mFormatter;
    private LinearLayout lay_title, lay_others, lay_foot;
    private Activity activity;

    public String vid;


    ImageView add, sub;
    VerticalSeekBar vBar;

    TextView backText;
    View back;

    public boolean playTime;

    /***
     * 点赞、分享
     */
    public Button btnZan, btnShare;
    private OnClickListener mZanListener, mShareListener;


    public Controller(Context context) {
        this(context, true);
        mContext = context;
    }

    public Controller(Context context, AttributeSet attrs) {
        super(context, attrs);

        mRootView = null;
        mContext = context;
        mUseFastForward = true;
        mFromXml = true;
    }

    public Controller(Context context, boolean useFastForward) {
        super(context);
        mContext = context;
        mUseFastForward = useFastForward;
    }

    public void removeHandlerCallback() {
        if (mHandler != null) {
            mHandler.removeCallbacksAndMessages(null);
            mHandler = null;
        }
    }

    @Override
    public void onFinishInflate() {
        if (mRootView != null) {
            initCtrlView(mRootView);
        }
    }

    public void setMediaPlayer(ControlOper player) {
        mPlayerCtrl = player;
        updatePausePlay();
        // updateFullScreen();
    }


    public void setAnchorView(ViewGroup view) {

        mAnchorVGroup = view;
        FrameLayout.LayoutParams frameParams = new FrameLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT);
        removeAllViews();

        View v = createCtrlView();
        addView(v, frameParams);
    }

    protected View createCtrlView() {

        LayoutInflater inflate = (LayoutInflater) mContext
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        mRootView = inflate.inflate(R.layout.controller, null);
        initCtrlView(mRootView);

        return mRootView;
    }


    private void initCtrlView(View v) {


        mBtnPause = (ImageButton) v.findViewById(R.id.pause);
        if (mBtnPause != null) {
            mBtnPause.requestFocus();
            mBtnPause.setOnClickListener(mPauseListener);
        }


        lay_title = (LinearLayout) v.findViewById(R.id.lay_titles);


        backText = (TextView) v.findViewById(R.id.back_text);
        backText.setTypeface(Constants.gettyperFace());
        back = v.findViewById(R.id.mediacontroller_back);
        back.setOnClickListener(mBackListener);
        initVolumeController(v);

        // By default these are hidden. They will be enabled when
        // setPrevNextListeners() is called
        mBtnNext = (ImageButton) v.findViewById(R.id.next);
        if (mBtnNext != null && !mFromXml && !mIsListenersSet) {
            mBtnNext.setVisibility(View.VISIBLE);
        }
        lay_others = (LinearLayout) v.findViewById(R.id.lay_others);
        lay_foot = (LinearLayout) v.findViewById(R.id.lay_foot);

        btnZan = (Button) v.findViewById(R.id.btn_videoplay_zan);
        if (btnZan != null && !mFromXml && !mIsListenersSet) {
            btnZan.setVisibility(View.VISIBLE);
        }
        btnShare = (Button) v.findViewById(R.id.btn_videoplay_share);
        if (btnShare != null && !mFromXml && !mIsListenersSet) {
            btnShare.setVisibility(View.VISIBLE);
        }


        mBtnPrev = (ImageButton) v.findViewById(R.id.prev);
        if (mBtnPrev != null && !mFromXml && !mIsListenersSet) {
            mBtnPrev.setVisibility(View.VISIBLE);
        }
        mBtnFullscreen = (ImageView) v.findViewById(R.id.fullscreen);
        if (mBtnFullscreen != null && !mFromXml && !mIsListenersSet) {
            mBtnFullscreen.setVisibility(VISIBLE);
        }


        mProgress = (SeekBar) v.findViewById(R.id.mediacontroller_progress);
        if (mProgress != null) {
            if (mProgress instanceof SeekBar) {
                SeekBar seeker = (SeekBar) mProgress;
                seeker.setOnSeekBarChangeListener(mSeekListener);
            }
            mProgress.setMax(1000);
        }

        mEndTime = (TextView) v.findViewById(R.id.time);
        mCurTime = (TextView) v.findViewById(R.id.time_current);
        mStrBuilder = new StringBuilder();
        mFormatter = new Formatter(mStrBuilder, Locale.getDefault());

        installPrevNextListeners();
    }


    public void hideScreen() {
        mBtnFullscreen.setVisibility(GONE);
    }


    public void setBackText(String text) {
        backText = (TextView) mRootView.findViewById(R.id.back_text);
        backText.setTypeface(Constants.gettyperFace());
        backText.setText(text);
    }

    public void hidet() {
        lay_title.setVisibility(GONE);
        backText.setVisibility(GONE);
        back.setVisibility(GONE);
    }

    public void hidelay_foot() {
        lay_foot.setVisibility(GONE);
    }

    public void showlay_foot() {
        lay_foot.setVisibility(VISIBLE);
    }

    public void zanHidet() {
        lay_others.setVisibility(VISIBLE);
    }

    public void hideZan() {
        lay_others.setVisibility(GONE);
        lay_title.setBackgroundColor(getResources().getColor(R.color.transparent));
    }

    public void zanSelect(int sid) {
        btnZan.setBackgroundResource(sid);
        btnZan.setBackgroundResource(R.drawable.videoplay_press_zan);
    }

    public void zanNormal() {
        btnZan.setBackgroundResource(R.drawable.videoplay_zan);
    }


    protected static final int PROGRESS_CHANGED = 0x101;
    AudioManager mAudioManager;

    void initVolumeController(View v) {

        mAudioManager = (AudioManager) mContext
                .getSystemService(Context.AUDIO_SERVICE);
        final Handler myHandler = new Handler() {
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case PROGRESS_CHANGED:
                        setVolum();
                    /* sendEmptyMessageDelayed(PROGRESS_CHANGED, 200); */
                        break;
                }
            }
        };

        class myVolThread implements Runnable {
            public void run() {
                while (!Thread.currentThread().isInterrupted() && isPlaying) {
//					L.i("checking system volume");
                    Message message = new Message();
                    message.what = PROGRESS_CHANGED;
                    myHandler.sendMessage(message);
                    try {
                        Thread.sleep(300);
                    } catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
                    }
                }
            }
        }
        add = (ImageView) v.findViewById(R.id.mediacontroller_volume_add);
        vBar = (VerticalSeekBar) v.findViewById(R.id.mediacontroller_progress_vo);
        sub = (ImageView) v.findViewById(R.id.mediacontroller_volume_sub);

        OnSeekBarChangeListener seekBarChangeListener = new OnSeekBarChangeListener() {
            public void onProgressChanged(SeekBar seekBar, int progress,
                                          boolean fromUser) {
                // TODO Auto-generated method stub
                mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC,
                        progress, 0);
            }

            public void onStartTrackingTouch(SeekBar seekBar) {
                // TODO Auto-generated method stub

            }

            public void onStopTrackingTouch(SeekBar seekBar) {
                // TODO Auto-generated method stub

            }

        };
        vBar.setOnSeekBarChangeListener(seekBarChangeListener);
        new Thread(new myVolThread()).start();
    }

    public void setFullScreen(){
        mBtnFullscreen.setImageResource(R.drawable.enter_full);
    }
    public void setscreen(){
        mBtnFullscreen.setImageResource(R.drawable.exit_full);
    }

    boolean isPlaying = true;

    private void setVolum() {
        int maxVolume = mAudioManager
                .getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        int currentVolume = mAudioManager
                .getStreamVolume(AudioManager.STREAM_MUSIC);
        vBar.setMax(maxVolume);
        vBar.setProgress(currentVolume);
    }

    /**
     * Show the controller on screen. It will go away automatically after 3
     * seconds of inactivity.
     */
    public void show() {
        show(DEFTIMEOUT);
    }

    /**
     * Disable pause or seek buttons if the stream cannot be paused or seeked.
     * This requires the control interface to be a MediaPlayerControlExt
     */
    private void disableUnsupportedButtons() {
        if (mPlayerCtrl == null) {
            return;
        }

        try {
            if (mBtnPause != null && !mPlayerCtrl.canPause()) {
                mBtnPause.setEnabled(false);
            }
            // if (mBtnRew != null && !mPlayerCtrl.canSeekBackward()) {
            // mBtnRew.setEnabled(false);
            // }
//			if (mBtnFfwd != null && !mPlayerCtrl.canSeekForward()) {
//				mBtnFfwd.setEnabled(false);
//			}
        } catch (IncompatibleClassChangeError ex) {

        }
    }

    public void show(int timeout) {
        if (!mIsShowing && mAnchorVGroup != null) {
            setProgress();
            if (mBtnPause != null) {
                mBtnPause.requestFocus();
            }
            disableUnsupportedButtons();

            FrameLayout.LayoutParams tlp = new FrameLayout.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.BOTTOM);

            mAnchorVGroup.addView(this, tlp);
            mIsShowing = true;
        }
        updatePausePlay();
        // updateFullScreen();

        mHandler.sendEmptyMessage(SHOW_PROGRESS);

        Message msg = mHandler.obtainMessage(FADE_OUT);
        if (timeout != 0) {
            mHandler.removeMessages(FADE_OUT);
            mHandler.sendMessageDelayed(msg, timeout);
        }

//        mPlayerCtrl.showTitle();
    }

    public boolean isShowing() {
        return mIsShowing;
    }

    /**
     * Remove the controller from the screen.
     */
    public void hide() {
        if (mAnchorVGroup == null) {
            return;
        }

        try {
            mAnchorVGroup.removeView(this);
            if (mHandler != null) {
                mHandler.removeMessages(SHOW_PROGRESS);
            }
        } catch (IllegalArgumentException ex) {
            Log.w("MediaController", "already removed");
        }
        mIsShowing = false;
        mPlayerCtrl.hiteTitle();
    }

    private String stringForTime(int timeMs) {
        int totalSeconds = timeMs / 1000;

        int seconds = totalSeconds % 60;
        int minutes = (totalSeconds / 60) % 60;
        int hours = totalSeconds / 3600;

        mStrBuilder.setLength(0);
        if (hours > 0) {
            return mFormatter.format("%d:%02d:%02d", hours, minutes, seconds)
                    .toString();
        } else {
            return mFormatter.format("%02d:%02d", minutes, seconds).toString();
        }
    }

    int position;
    int duration ;
    public int setProgress() {
        if (mPlayerCtrl == null || mIsDragging) {
            return 0;
        }

         position = mPlayerCtrl.getCurPosition();
         duration = mPlayerCtrl.getDuration();
        if (mProgress != null) {
            if (duration > 0) {
                // use long to avoid overflow
                long pos = 1000L * position / duration;
                mProgress.setProgress((int) pos);
            }
            int percent = mPlayerCtrl.getBufPercent();
            mProgress.setSecondaryProgress(percent * 10);
        }

        if (mEndTime != null)
            mEndTime.setText(stringForTime(duration));

        if (mCurTime != null)
            mCurTime.setText(stringForTime(position));


//        timer.schedule(timerTask,5000);
        if(duration*0.8<position){
            watchRecord();

        }
        return position;
    }



    private Timer timer = new Timer();
    private TimerTask timerTask = new TimerTask() {
        @Override
        public void run() {
            Message message = new Message();
            message.what = 1;
            handler.sendMessage(message);
        }
    };
    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            boolean isWatch = (boolean)SharedPreferencesUtils.getValue(mContext,SharedPreferencesUtils.user_isWatch,true);
            if(duration*0.8<position){
                if(timer !=null){
                    timer.cancel();
                }
                watchRecord();

            }
        }
    };

    private void watchRecord(){
        UserInfo userInfo  = new UserInfo();
        HashMap<String,String> params = new HashMap<>();
        params.put("uid", userInfo.userID);
        params.put("videoId", vid);
        TaskExecutor.getInstance().execute(new MyPostRequestTask(params, UrlConsts.USER_WATCH_RECORD) {
            @Override
            protected void handleResponse(String response) {
                if(response!=null){
                    SharedPreferencesUtils.getValue(mContext,SharedPreferencesUtils.user_isWatch,false);
                }

            }
        });
    }



    @Override
    public boolean onTouchEvent(MotionEvent event) {
        final int action = MotionEventCompat.getActionMasked(event);

        switch (action) {
            case MotionEvent.ACTION_UP:
                if (canHideTitle) {
                    if (mIsShowing) {
                        hide();
                    } else {
                        show(DEFTIMEOUT);
                    }
                }
                break;
            default:
                break;
        }
        return true;
    }

    @Override
    public boolean onTrackballEvent(MotionEvent ev) {
        show(DEFTIMEOUT);
        return false;
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (mPlayerCtrl == null) {
            return true;
        }

        int keyCode = event.getKeyCode();
        final boolean uniqueDown = event.getRepeatCount() == 0
                && event.getAction() == KeyEvent.ACTION_DOWN;
        if (keyCode == KeyEvent.KEYCODE_HEADSETHOOK
                || keyCode == KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE
                || keyCode == KeyEvent.KEYCODE_SPACE) {
            if (uniqueDown) {
                doPauseResume();
                show(DEFTIMEOUT);
                if (mBtnPause != null) {
                    mBtnPause.requestFocus();
                }
            }
            return true;
        } else if (keyCode == KeyEvent.KEYCODE_MEDIA_PLAY) {
            if (uniqueDown && !mPlayerCtrl.isPlaying()) {
                mPlayerCtrl.start();
                updatePausePlay();
                show(DEFTIMEOUT);
            }
            return true;
        } else if (keyCode == KeyEvent.KEYCODE_MEDIA_STOP
                || keyCode == KeyEvent.KEYCODE_MEDIA_PAUSE) {
            if (uniqueDown && mPlayerCtrl.isPlaying()) {
                mPlayerCtrl.pause();
                updatePausePlay();
                show(DEFTIMEOUT);
            }
            return true;
        } else if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN
                || keyCode == KeyEvent.KEYCODE_VOLUME_UP
                || keyCode == KeyEvent.KEYCODE_VOLUME_MUTE) {
            // don't show the controls for volume adjustment
            return super.dispatchKeyEvent(event);
        } else if (keyCode == KeyEvent.KEYCODE_BACK
                || keyCode == KeyEvent.KEYCODE_MENU) {
            if (uniqueDown) {
                hide();
            }
            return true;
        }

        show(DEFTIMEOUT);
        return super.dispatchKeyEvent(event);
    }


    private View.OnClickListener mBackListener = new View.OnClickListener() {
        public void onClick(View v) {
            isPlaying = false;
            ((BaseActivity) mContext).finish();
        }
    };

    private View.OnClickListener mPauseListener = new View.OnClickListener() {
        public void onClick(View v) {
            doPauseResume();
            show(DEFTIMEOUT);
        }
    };

//	private View.OnClickListener mFullscreenListener = new View.OnClickListener() {
//		public void onClick(View v) {
////			doToggleFullscreen();
////			show(DEFTIMEOUT);
//		}
//	};

    public void updatePausePlay() {
        if (mRootView == null || mBtnPause == null || mPlayerCtrl == null) {
            return;
        }

        if (mPlayerCtrl.isPlaying()) {
            mBtnPause
                    .setImageResource(R.drawable.zanting);
        } else {
            mBtnPause
                    .setImageResource(R.drawable.bofang);
        }
    }


    private void doPauseResume() {
        if (mPlayerCtrl.isPlaying()) {
            mPlayerCtrl.pause();
            updatePausePlay();
            show(DEFTIMEOUT);
        } else {
//			mPlayerCtrl
            mPlayerCtrl.start();
            updatePausePlay();
            show(DEFTIMEOUT);
        }
    }

    public void doToggleFullscreen() {
        if (mPlayerCtrl == null) {
            return;
        }
        mPlayerCtrl.fullScreen();
    }

    private boolean canHideTitle= true;
    private OnSeekBarChangeListener mSeekListener = new OnSeekBarChangeListener() {
        public void onStartTrackingTouch(SeekBar bar) {
            show(3600000);

            mIsDragging = true;
            mHandler.removeMessages(SHOW_PROGRESS);
            canHideTitle = false;
        }

        public void onProgressChanged(SeekBar bar, int progress,
                                      boolean fromuser) {
            if (mPlayerCtrl == null) {
                return;
            }

            if (!fromuser) {
                // We're not interested in programmatically generated changes to
                // the progress bar's position.
                return;
            }

            long duration = mPlayerCtrl.getDuration();
            long newposition = (duration * progress) / 1000L;
            mPlayerCtrl.seekTo((int) newposition);
            if (mCurTime != null)
                mCurTime.setText(stringForTime((int) newposition));
            }

        public void onStopTrackingTouch(SeekBar bar) {
            mIsDragging = false;
            setProgress();
            updatePausePlay();
            show(DEFTIMEOUT);

            mHandler.sendEmptyMessage(SHOW_PROGRESS);
            canHideTitle = true;
        }
    };

    @Override
    public void setEnabled(boolean enabled) {
        if (mBtnPause != null) {
            mBtnPause.setEnabled(enabled);
        }
//		if (mBtnFfwd != null) {
//			mBtnFfwd.setEnabled(enabled);
//		}
        // if (mBtnRew != null) {
        // mBtnRew.setEnabled(enabled);
        // }
        if (mBtnNext != null) {
            mBtnNext.setEnabled(enabled && mNextListener != null);
        }
        if (mBtnPrev != null) {
            mBtnPrev.setEnabled(enabled && mPrevListener != null);
        }
        if (btnZan != null) {
            btnZan.setEnabled(enabled && mZanListener != null);
        }
        if (btnShare != null) {
            btnShare.setEnabled(enabled && mShareListener != null);
        }
        if (mBtnFullscreen != null) {
            mBtnFullscreen.setEnabled(enabled && mFullScreenListener != null);
        }
        if (mProgress != null) {
            mProgress.setEnabled(enabled);
        }
        disableUnsupportedButtons();
        super.setEnabled(enabled);
    }

    @SuppressLint("NewApi")
    @Override
    public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
        super.onInitializeAccessibilityEvent(event);
        event.setClassName(Controller.class.getName());
    }

    @SuppressLint("NewApi")
    @Override
    public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
        super.onInitializeAccessibilityNodeInfo(info);
        info.setClassName(Controller.class.getName());
    }

    private View.OnClickListener mRewListener = new View.OnClickListener() {
        public void onClick(View v) {
            if (mPlayerCtrl == null) {
                return;
            }

            int pos = mPlayerCtrl.getCurPosition();
            pos -= 5000; // milliseconds
            mPlayerCtrl.seekTo(pos);
            setProgress();

            show(DEFTIMEOUT);
        }
    };

    private View.OnClickListener mFfwdListener = new View.OnClickListener() {
        public void onClick(View v) {
            if (mPlayerCtrl == null) {
                return;
            }

            int pos = mPlayerCtrl.getCurPosition();
            pos += 15000; // milliseconds
            mPlayerCtrl.seekTo(pos);
            setProgress();

            show(DEFTIMEOUT);
        }
    };

    private void installPrevNextListeners() {
        if (mBtnNext != null) {
            mBtnNext.setOnClickListener(mNextListener);
            mBtnNext.setEnabled(mNextListener != null);
        }

        if (mBtnPrev != null) {
            mBtnPrev.setOnClickListener(mPrevListener);
            mBtnPrev.setEnabled(mPrevListener != null);
        }
        if (btnZan != null) {
            btnZan.setOnClickListener(mZanListener);
            btnZan.setEnabled(mZanListener != null);

        }

        if (btnShare != null) {
            btnShare.setOnClickListener(mShareListener);
            btnShare.setEnabled(mShareListener != null);

        }
        if (mBtnFullscreen != null) {
            mBtnFullscreen.setOnClickListener(mFullScreenListener);
            mBtnFullscreen.setEnabled(mFullScreenListener != null);
        }
    }

    public void setPrevNextListeners(View.OnClickListener next,
                                     View.OnClickListener prev, OnClickListener mFull, OnClickListener zan, OnClickListener share) {
        mNextListener = next;
        mPrevListener = prev;
        mFullScreenListener = mFull;
        mZanListener = zan;
        mShareListener = share;
        mIsListenersSet = true;


        if (mRootView != null) {
            installPrevNextListeners();

            if (mBtnNext != null && !mFromXml) {
                mBtnNext.setVisibility(View.GONE);
            }
            // if (mBtnPrev != null && !mFromXml) {
            // mBtnPrev.setVisibility(View.GONE);
            // }
        }
    }

    public interface ControlOper {
        void start();

        void pause();

        int getDuration();

        int getCurPosition();

        void seekTo(int pos);

        boolean isPlaying();

        int getBufPercent();

        boolean canPause();

        boolean canSeekBackward();

        boolean canSeekForward();

        boolean isFullScreen();

        void showTitle();

        void hiteTitle();

        void fullScreen();
    }

    private static class MsgHandler extends Handler {

        private final WeakReference<Controller> mView;

        MsgHandler(Controller view) {
            mView = new WeakReference<Controller>(view);
        }

        @Override
        public void handleMessage(Message msg) {

            Controller view = mView.get();
            if (view == null || view.mPlayerCtrl == null) {
                return;
            }

            int pos;
            switch (msg.what) {

                case FADE_OUT: {
                    view.hide();
                    break;
                }

                case SHOW_PROGRESS: {

                    if (view.mPlayerCtrl.isPlaying()) {
                        pos = view.setProgress();
                    } else {
                        return;
                    }

                    if (!view.mIsDragging && view.mIsShowing
                            && view.mPlayerCtrl.isPlaying()) {

                        msg = obtainMessage(SHOW_PROGRESS);
                        sendMessageDelayed(msg, 1000 - (pos % 1000));
                    }
                    break;
                }
            }
        }
    }
}
